<template>
  <div >
    <!-- 表单部分 -->
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm"
             label-width="100px" class="el-main-form" style="position: relative">

      <span style="position: absolute;left: 20px;top: 50px">上传头像</span>
      <el-form-item prop="avatar">
        <!-- show-file-list 是否显示已上传文件列表 auto-upload是否在选取文件后立即进行上传 -->
        <el-upload
            class="avatar-uploader"
            name="picFile"
            action="http://localhost:8080/upload/avatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
        >
          <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username" required>
        <el-input type="text" v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" required>
        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass" required>
        <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname" required>
        <el-input type="text" v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender" style="width: 250px" required>
        <el-radio-group v-model="ruleForm.gender">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday" required>
            <el-date-picker type="date" placeholder="选择日期或输入 xxxx-xx-xx"
                            v-model="ruleForm.birthday" style="width: 280px;">
            </el-date-picker>
      </el-form-item>
      <el-form-item label="电话号码" prop="phone" required>
        <el-input type="text" v-model.number="ruleForm.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email" required>
        <el-input type="text" v-model="ruleForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address" required>
        <el-cascader size="large" :options="options" v-model="ruleForm.address" style="width: 280px;"
                     @change="handleChangeChina" placeholder="请选择省市区"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 250px;" :plain="true" @click="submitForm('ruleForm')">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {regionData, CodeToText} from 'element-china-area-data'//引入element-china-area-data插件实现省市区联动
export default {
  data() {
    var validateuserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error('请输入正确的手机号'));
        }
      }
    };
    return {
      ruleForm: {
        username: '',
        password: '',
        checkPass: '',
        nickname: '',
        gender: '',
        birthday: '',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        phone: '',
        email: '',
        address: [],// 省市区绑定数组
      },
      line: '',
      options: regionData,// 选择格式
      rules: {// 校验
        username: [
          {required: true, validator: validateuserName, trigger: 'blur'}
        ],
        password: [
          {required: true, validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {required: true, validator: validatePass2, trigger: 'blur'}
        ],
        phone: [
          {required: true, validator: validatePhone, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址'}
        ],
        birthday: [
          {type: 'date', required: true, message: "请输入正确的日期", trigger: 'change'}
        ],
        nickname: [
          {required: true, message: '昵称不能为空', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请选择用户地址', trigger: 'change'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ]
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => { // 表单验证
        if (valid) {
          // alert('submit!');
          let url = 'http://localhost:8080/users/reg';
          // console.log('url >> ' + url)
          // console.log(this.ruleForm.url)
          this.ruleForm.address = this.line
          this.axios.post(url, this.ruleForm).then((response) => {
            let json = response.data
            let state = json.state
            if (state == 20000) {
              this.$message({
                showClose: true,
                message: '注册成功！即将回到登录页面',
                type: 'success'
              });
              setTimeout(() => {
                location.href = "/login"
              }, 1000)
            } else {
              console.log(json.message);
              this.$message.error(json.message);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleAvatarSuccess(response,file,fileList){
      console.log("文件上传完成,图片名="+response)
      this.ruleForm.avatar = response
    },
    handleChangeChina(value) {// 事件触发
      //value是省市区类似id 返回数组 [110000,110100,110101]，可以当发到后端存储，回显数据
      //汉字
      if (value[1] != null && value[2] != null) {
        this.line =
            CodeToText[value[0]] +
            CodeToText[value[1]] +
            CodeToText[value[2]]
      } else {
        if (value[1] != null) {
          this.line = CodeToText[value[0]] + CodeToText[value[1]]
        } else {
          this.line = CodeToText[value[0]]
        }
      }
    }
  }
}
</script>
<style>
.el-main-form {
  margin: 30px 30px 0 0;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  border-radius: 50%;
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 125px;
  line-height: 125px;
  text-align: center;
}

.avatar {
  width: 125px;
  height: 125px;
  display: block;
}

</style>